package com.leyou.filter;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.pojo.CookieUtils;
import com.leyou.config.FilterProperties;
import com.leyou.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.FileFilter;
import java.util.List;

@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})
public class LoginFilter extends ZuulFilter {

    @Autowired
    private FilterProperties filterProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {

        // 获取白名单内容
        List<String> allowPaths = filterProperties.getAllowPaths();
        // 获取 context 上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取域对象
        HttpServletRequest request = context.getRequest();
        // 获取请求路径
        String requestURI = request.getRequestURI();
        // 遍历白名单 如果包含请求路径 就不拦截
        for (String allowPath : allowPaths) {
            if (StringUtils.contains(requestURI,allowPath)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 获取 context 上下文
        RequestContext context = RequestContext.getCurrentContext();

        // 获取域对象
        HttpServletRequest request = context.getRequest();

        // 获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());

        // 校验

        try {
            // 检验通过 放行
            JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            // 检验不通过 不转发
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }

        return null;
    }
}
